package com.wechat.scheme.exception;


import com.wechat.scheme.response.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.persistence.EntityNotFoundException;

@ControllerAdvice
public class ExceptionHandlers {

    static final Log LOG = LogFactory.getLog(ExceptionHandlers.class);

    public ExceptionHandlers() {
    }

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseBody
    public Response<String> handlerIlleageEx(Exception ex) {
        LOG.error("IllegalArgumentException", ex);
        return Response.fail(ex.toString());
    }

    @ExceptionHandler({EntityNotFoundException.class})
    @ResponseBody
    public Response<String> handlerEntityNoFoundEx(EntityNotFoundException ex) {
        return Response.fail( ex.toString());
    }

    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    public Response<String> handlerBussEx(BusinessException ex) {
        LOG.error("BusinessException:"+ex.getData(),ex);
        return StringUtils.isEmpty(ex.getCode()) ? Response.fail(ex.getMessage()) : Response.fail(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Response<String> throwable(Exception exception) {
        LOG.error((Object)exception.getMessage(), exception);
        return Response.fail( 500,"msg_system_error", exception.toString());
    }


    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public Response handleUnauthorizedException() {
        LOG.error("Returning HTTP 401 Bad Request cause by Unauthorized ");
        return Response.fail(HttpStatus.UNAUTHORIZED.value(),HttpStatus.UNAUTHORIZED.name());
    }

}
